JavaScript provides a built-in Math object that allows you to perform mathematical operations. Below are some common Math functions.
The Math.round() function rounds a number to the nearest integer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.round(4.7));
</Script>
</body>
</html>
// Outputs: 5
The Math.random() function returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.random());
</Script>
</body>
</html>
// Outputs a random number
The Math.max() function returns the largest of the zero or more numbers given as input parameters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.max(10, 20, 30));
</Script>
</body>
</html>
// Outputs: 30
The Math.min() function returns the smallest of the zero or more numbers given as input parameters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.min(10, 20, 30));
</Script>
</body>
</html>
// Outputs: 10
The Math.sqrt() function returns the square root of a number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.sqrt(16));
</Script>
</body>
</html>
// Outputs: 4
The Math.pow() function returns the base to the exponent power.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.pow(2, 3));
</Script>
</body>
</html>
// Outputs: 8
The Math.ceil() function returns the smallest integer greater than or equal to a given number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.ceil(4.2));
</Script>
</body>
</html>
// Outputs: 5
The Math.floor() function returns the largest integer less than or equal to a given number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
console.log(Math.floor(4.9));
</Script>
</body>
</html>
// Outputs: 4